<?php

namespace addons\csmitsm\library\xcore\xcore\base;

use think\Loader;
use addons\csmitsm\library\xcore\xcore\base\XcAApi;
use addons\csmitsm\library\xcore\xcore\utils\XcAdminSessionUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcConfigUtils;

/**
 * Api的基础类(api admin control的基类)
 * 需要写在 addons/controller 下
 */
abstract class XcAAdminApi extends XcAApi
{

    protected function _initialize()
    {
        check_cors_request();
        check_ip_allowed();

        [$controllername, $path] = [null, null];
        if (true) {
            $controllername = Loader::parseName($this->request->controller());
            $actionname = strtolower($this->request->action());
            $path = 'addons/' . XcConfigUtils::getAddonCode() . "/" . str_replace('.', '/', $controllername) . '/' . $actionname;
        }

        $this->loadlang($controllername);

        $noNeedLogin = $this->toLowerArray($this->noNeedLogin);
        $noNeedRight = $this->toLowerArray($this->noNeedRight);

        // 既没有*, path也不在noNeedLogin中, 又没有登录, 则提示用户登录
        if (!in_array("*", $this->noNeedLogin) && !in_array($actionname, $noNeedLogin) && XcAdminSessionUtils::getUserId(false) == null) {
            $this->error(__('Please login first'));
        }
        $admin_id = XcAdminSessionUtils::getUserId();
        // 即没有*, path也不在noNeedRight中, 又没有path的权限, 则提示没有权限
        if ($admin_id != 1 && !in_array("*", $this->noNeedRight) && !in_array($actionname, $noNeedRight) && XcAdminSessionUtils::matchRule($path) === false) {
            $this->error(__('You have no permission'));
        }
        $this->xinit();
    }

    private function toLowerArray($array)
    {
        $sr = [];
        foreach ($array as $item) {
            $sr[] = strtolower($item);
        }
        return $sr;
    }
}
